package cn.sad.bjsx.starter.environment;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * 在spring上下文构建之前可以设置一些系统配置
 * 
 * @author sad
 *
 */
public class BjsxEnvironment implements EnvironmentPostProcessor {

	/** 国际化文件base路径 */
	public static final String SMB = "spring.messages.basename";

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		System.out.println("********************************************************************************");
		System.out.println("************ 【cn.sad.bjsx.starter.environment.BjsxEnvironment】 ***********************");

		// --- 扫描每个jar，动态构建国际化文件base路径
		String springMessagesBasename = dyncBuildSpringMessagesBasename();
		if (StringUtils.isNotBlank(springMessagesBasename)) {
			System.out.println("");
			System.out.println("spring.messages.basename: " + springMessagesBasename);

			// 自定义修改后添加进去覆盖
			HashMap<String, Object> map = new HashMap<>(1);
			map.put(SMB, springMessagesBasename);
			PropertySource<?> source = new MapPropertySource("gs_dync", map);
			environment.getPropertySources().addFirst(source);
		}

		System.out.println("");

		// 输出所有配置的属性
		MutablePropertySources propertySources = environment.getPropertySources();
		Iterator<PropertySource<?>> iterator = propertySources.iterator();
		while (iterator.hasNext()) {
			PropertySource<?> next = iterator.next();
			if (next instanceof OriginTrackedMapPropertySource) {
				OriginTrackedMapPropertySource originTrackedMapPropertySource = (OriginTrackedMapPropertySource) next;
				System.out.println("## ---- " + getConfigFilename(originTrackedMapPropertySource.getName()) + " ----");
				Map<String, Object> source = originTrackedMapPropertySource.getSource();
				for (Map.Entry<String, Object> entry : source.entrySet()) {
					System.out.println(entry.getKey() + "=" + entry.getValue().toString());
				}
				System.out.println("");
			}
		}

		System.out.println("********************************************************************************");
		System.out.println("");
	}

	/**
	 * 扫描每个jar，动态构建国际化文件base路径
	 */
	private String dyncBuildSpringMessagesBasename() {
		String basename = "";

		try {
			String basePathName = "static/i18n/";
			Set<String> nameSet = new HashSet<String>();

			PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			Resource[] resources = resolver.getResources("classpath*:/" + basePathName + "*.properties");

			for (Resource resource : resources) {
				String name = resource.getFilename();
				if (name.indexOf("_") != -1) {
					name = name.substring(0, name.indexOf("_"));
				} else {
					name = name.substring(0, name.indexOf("."));
				}
				nameSet.add(basePathName + name);
			}
			if (CollectionUtils.isNotEmpty(nameSet)) {
				for (String name : nameSet) {
					basename += name + ",";
				}
				return StringUtils.removeEnd(basename, ",");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return basename;
	}

	/**
	 * 获取配置文件的名字
	 */
	private String getConfigFilename(String propertySourceName) {
		if (StringUtils.isBlank(propertySourceName)) {
			return "";
		}
		return StringUtils.substring(propertySourceName, StringUtils.indexOf(propertySourceName, "[") + 1, StringUtils.indexOf(propertySourceName, "]"));
	}

}
